/*
 * @Author: your name
 * @Date: 2020-08-19 08:14:50
 * @LastEditTime: 2020-08-27 17:09:51
 * @LastEditors: 王娆
 * @Description: In User Settings Edit
 * @FilePath: \ademo\vue-exam-demo\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import Cookies from 'js-cookie'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function repalce(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach(async(to,from,next)=>{
  let userId = sessionStorage.getItem('user_id')
  let identity_text=sessionStorage.getItem('identity_text')
  if(userId) {
    //判断页面有没有刷新
    if(store.state.GetAuth.filterRouter.length === 0){
      await store.dispatch('GetAuth/getRoutes',identity_text)
      next(to.fullPath)
    }else{
      next()
    }
    if(to.path === '/login'){
      Cookies.remove('token')
      next()
    }else{
      next()
    }
  }else {
    next()
  }
})

export default router
